import './styles.scss'
import { BackgroundPlugin, ColorPlugin, EmojiPlugin, ImagePlugin, LinkPlugin, SylEditor } from '@syllepsis/access-react'
import { ToolbarInlineLoader, ToolbarLoader } from '@syllepsis/editor'
import {
    AlignCenterPlugin,
    AlignJustifyPlugin,
    AlignLeftPlugin,
    AlignRightPlugin,
    AudioPlugin,
    BlockQuotePlugin,
    BoldPlugin,
    BulletListPlugin,
    FontSizePlugin,
    FormatClearPlugin,
    FormatPainterPlugin,
    HeaderPlugin,
    HrPlugin,
    ItalicPlugin,
    LetterSpacePlugin,
    LineHeightPlugin,
    LineIndentPlugin,
    ListItemPlugin,
    OrderedListPlugin,
    ParagraphPlugin,
    RedoPlugin,
    SpaceAfterPlugin,
    SpaceBeforePlugin,
    SpaceBothPlugin,
    StrikePlugin,
    SubPlugin,
    SupPlugin,
    UnderlinePlugin,
    UndoPlugin,
    VideoPlugin
} from '@syllepsis/plugin-basic'
import { EventChannel, SylApi } from '@syllepsis/adapter'
import { CodeBlockPlugin } from '@syllepsis/plugin-code-block'
import { TablePlugin } from '@syllepsis/plugin-table'
import React, { useState } from 'react'
import { Form, Button, Input, Modal, Radio, Card } from 'antd'
import { withRouter } from 'react-router-dom'
import { useRequest } from 'ahooks'
import { requestWrapper } from '@/utils/request'
import newAPI from '@/services/new'
import queryString from 'query-string'
import UploadImg from '@/components/UploadImg'

const UpdateNew = props => {
    const [plugins] = useState([
        new RedoPlugin(),
        new UndoPlugin(),
        new ColorPlugin(),
        new BoldPlugin(),
        new BlockQuotePlugin(),
        new ListItemPlugin({
            matchInnerTags: ['section', 'p'],
            allowedLineHeights: [],
            allowedSpaceBefores: [],
            allowedSpaceAfters: { default: true, value: 20 },
            allowedSpaceBoths: []
        }),
        new BulletListPlugin(),
        new OrderedListPlugin(),
        new CodeBlockPlugin({ lineNumbers: false }),
        new HrPlugin(),
        new HeaderPlugin(),
        new BackgroundPlugin(),
        new ItalicPlugin(),
        new SubPlugin(),
        new SupPlugin(),
        new StrikePlugin(),
        new UnderlinePlugin(),
        new ParagraphPlugin({
            addMatchTags: ['section'],
            allowedAligns: ['left', 'center', 'right', 'justify'],
            allowedClass: [],
            allowedLineHeights: [],
            allowedLineIndents: [],
            allowedSpaceBefores: [],
            allowedSpaceAfters: { default: true, value: 20 },
            allowedSpaceBoths: []
        }),
        new FormatClearPlugin(),
        new FontSizePlugin({
            allowedValues: [12, 14, 16, { value: 17, default: true }, 18, 20, 24, 32],
            values: [12, 14, 16, { value: 17, default: true }, 18, 20, 24, 32],
            unit: 'px'
        }),
        new LetterSpacePlugin({
            allowedValues: [0, 0.5, 1, 1.5]
        }),
        new AlignLeftPlugin(),
        new AlignCenterPlugin(),
        new AlignRightPlugin(),
        new AlignJustifyPlugin(),
        new SpaceBeforePlugin({
            values: [0, 4, 8, 12, 16, { value: 20, default: true }, 24, 28, 30]
        }),
        new SpaceAfterPlugin({
            values: [0, 4, 8, 12, 16, { value: 20, default: true }, 24, 28, 30]
        }),
        new SpaceBothPlugin({
            values: [0, 4, 8, 12, 16, { value: 20, default: true }, 24, 28, 30]
        }),
        new LineHeightPlugin({
            values: [1, 1.5, { value: 1.75, default: true }, 1.88, 2, 3]
        }),
        new LineIndentPlugin(),
        new FormatPainterPlugin(),
        new TablePlugin({
            button: {
                activeColor: '#FF0F0F',
                trigger: 'click'
            },
            columnResize: { handleWidth: 5, cellMinWidth: 24 },
            table: {
                allowTableNodeSelection: false,
                defaultCellWidth: 100,
                useTableHeader: false
            }
        }),
        new ImagePlugin({
            uploader: (f, attrs) =>
                new Promise(resolve => {
                    setTimeout(() => {
                        resolve({
                            src: attrs.src
                        })
                    }, 1500)
                }),
            disableCaption: true
        }),
        new VideoPlugin({
            uploader: async file =>
                Promise.resolve({
                    src: URL.createObjectURL(file),
                    size: file.size,
                    type: file.type,
                    title: file.name
                })
        }),
        new LinkPlugin(),
        new AudioPlugin({
            uploader: file =>
                Promise.resolve({
                    src: URL.createObjectURL(file)
                })
        }),
        new EmojiPlugin()
    ])

    const [module] = useState({
        toolbar: {
            Ctor: ToolbarLoader,
            option: {
                tools: [
                    UndoPlugin.getName(),
                    RedoPlugin.getName(),
                    // HeaderPlugin.getName(),
                    // BulletListPlugin.getName(),
                    // OrderedListPlugin.getName(),
                    CodeBlockPlugin.getName(),
                    BlockQuotePlugin.getName(),
                    BoldPlugin.getName(),
                    ItalicPlugin.getName(),
                    UnderlinePlugin.getName(),
                    StrikePlugin.getName(),
                    FontSizePlugin.getName(),
                    LetterSpacePlugin.getName(),
                    BackgroundPlugin.getName(),
                    FormatClearPlugin.getName(),
                    FormatPainterPlugin.getName(),
                    ColorPlugin.getName(),
                    // ImagePlugin.getName(),
                    VideoPlugin.getName(),
                    AudioPlugin.getName(),
                    HrPlugin.getName(),
                    LinkPlugin.getName(),
                    SubPlugin.getName(),
                    SupPlugin.getName(),
                    EmojiPlugin.getName(),
                    TablePlugin.getName(),
                    [
                        AlignLeftPlugin.getName(),
                        AlignCenterPlugin.getName(),
                        AlignRightPlugin.getName(),
                        AlignJustifyPlugin.getName()
                    ],
                    SpaceBeforePlugin.getName(),
                    SpaceAfterPlugin.getName(),
                    SpaceBothPlugin.getName(),
                    LineHeightPlugin.getName(),
                    LineIndentPlugin.getName()
                ],
                tooltips: {
                    [RedoPlugin.getName()]: '重做',
                    [UndoPlugin.getName()]: '撤销',
                    [HeaderPlugin.getName()]: '标题',
                    [BulletListPlugin.getName()]: '无序列表',
                    [OrderedListPlugin.getName()]: '有序列表',
                    [CodeBlockPlugin.getName()]: '代码块',
                    [BlockQuotePlugin.getName()]: '引用',
                    [BoldPlugin.getName()]: '加粗',
                    [ItalicPlugin.getName()]: '斜体',
                    [UnderlinePlugin.getName()]: '下划线',
                    [StrikePlugin.getName()]: '删除线',
                    [FontSizePlugin.getName()]: '字体大小',
                    [LetterSpacePlugin.getName()]: '字间距',
                    [BackgroundPlugin.getName()]: '背景色',
                    [FormatPainterPlugin.getName()]: '格式刷',
                    [FormatClearPlugin.getName()]: '清除格式',
                    [ColorPlugin.getName()]: '颜色',
                    [ImagePlugin.getName()]: '图片',
                    [VideoPlugin.getName()]: '视频',
                    [AudioPlugin.getName()]: '音频',
                    [HrPlugin.getName()]: '分割线',
                    [LinkPlugin.getName()]: '超链接',
                    [SubPlugin.getName()]: '下标',
                    [SupPlugin.getName()]: '上标',
                    [EmojiPlugin.getName()]: 'emoji表情',
                    [TablePlugin.getName()]: '表格',
                    [SpaceBeforePlugin.getName()]: '段前距',
                    [SpaceAfterPlugin.getName()]: '段后距',
                    [SpaceBothPlugin.getName()]: '两端缩进',
                    [LineHeightPlugin.getName()]: '行高',
                    [LineIndentPlugin.getName()]: '行间距'
                }
            }
        },
        toolbarInline: {
            Ctor: ToolbarInlineLoader,
            option: {
                tools: [
                    FormatClearPlugin.getName(),
                    BoldPlugin.getName(),
                    ItalicPlugin.getName(),
                    UnderlinePlugin.getName(),
                    StrikePlugin.getName(),
                    '|',
                    AlignLeftPlugin.getName(),
                    HeaderPlugin.getName(),
                    FontSizePlugin.getName(),
                    LetterSpacePlugin.getName(),
                    {
                        content: [OrderedListPlugin.getName(), BulletListPlugin.getName()],
                        contentOption: { tipDirection: 'up' }
                    },
                    'color'
                ],
                tooltips: {
                    [FormatClearPlugin.getName()]: '清除格式',
                    [BoldPlugin.getName()]: '加粗',
                    [ItalicPlugin.getName()]: '斜体',
                    [UnderlinePlugin.getName()]: '下划线',
                    [StrikePlugin.getName()]: '删除线',
                    [AlignLeftPlugin.getName()]: '左对齐',
                    [HeaderPlugin.getName()]: '标题',
                    [FontSizePlugin.getName()]: '字体大小',
                    [LetterSpacePlugin.getName()]: '字间距',
                    color: '颜色'
                }
            }
        }
    })
    const { getFieldDecorator } = props.form
    const [editor, setEditor] = useState()
    const [visible, setVisible] = useState(false)
    const { newId } = queryString.parse(props.location.search)
    const [content, setContent] = useState(undefined)
    const [path, setPath] = useState(undefined)
    const [count, setCount] = useState()
    const { data: newDetail = {}, run: getDetail } = useRequest(
        () =>
            requestWrapper(newAPI.detail.bind(null, newId), {
                // autoSuccess: true,
            }),
        {
            // manual: true,
            onSuccess: () => {
                const content = JSON.parse(newDetail.content)
                editor.setContent(content)
            }
        }
    )

    const { run: updateNew } = useRequest(
        params =>
            requestWrapper(newAPI.updateNew.bind(null, newId, params), {
                autoSuccess: true
            }),
        {
            manual: true,
            onSuccess: () => {
                props.history.push('/user/my')
            }
        }
    )

    const handleOk = () => {
        props.form.validateFields((err, values) => {
            if (!err) {
                values.content = content
                values.state = 'audit'
                values.newsImg = path || newDetail.newsImg || '/assets/dog.jpg'
                console.log(values)
                updateNew(values)
            }
        })
        setVisible(false)
    }
    const hold = () => {
        props.form.validateFields((err, values) => {
            if (!err) {
                values.content = content
                values.state = 'hold'
                values.newsImg = path || 'assets/newImg.jpg'
                console.log(values)
                updateNew(values)
            }
        })
        setVisible(false)
    }
    const handleCancel = () => {
        setVisible(false)
    }

    const submit = () => {
        let text = undefined
        setVisible(true)
        text = editor.getContent()
        let t = JSON.stringify(text)
        setContent(t)
    }

    const cardTitle = () => {
        return (
            <div>
                <span className='title'>修改新闻</span>
                <Button
                    className='btn'
                    onClick={() => {
                        submit()
                        setCount(true)
                    }}
                    type='primary'>
                    提交
                </Button>
                <Button
                    className='btn'
                    onClick={() => {
                        submit()
                        setCount(false)
                    }}
                    type='primary'>
                    暂存
                </Button>
            </div>
        )
    }

    return (
        <div className='update_editor'>
            <Modal title='Basic Modal' visible={visible} onOk={count ? handleOk : hold} onCancel={handleCancel}>
                <Form>
                    <Form.Item label='请确认您的标题'>
                        {getFieldDecorator('title', {
                            rules: [{ required: true, message: '请输入标题' }],
                            initialValue: newDetail.title
                        })(<Input />)}
                    </Form.Item>
                    <Form.Item label='简述'>
                        {getFieldDecorator('desc', { initialValue: newDetail.desc })(<Input />)}
                    </Form.Item>
                    <Form.Item label='类别'>
                        {getFieldDecorator('label', {
                            rules: [{ required: true, message: '请选择类别' }],
                            initialValue: newDetail.label
                        })(
                            <Radio.Group>
                                <Radio value={'military'}>军事</Radio>
                                <Radio value={'science'}>科技</Radio>
                                <Radio value={'game'}>游戏</Radio>
                                <Radio value={'pastime'}>娱乐</Radio>
                                <Radio value={'health'}>健康</Radio>
                                <Radio value={'car'}>汽车</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item label='封面'>
                        <UploadImg setPath={setPath} />
                    </Form.Item>
                </Form>
            </Modal>
            <Card type='inner' title={cardTitle()} className='card'>
                <SylEditor
                    // editable={false}
                    getEditor={editor => {
                        window.editor = editor
                        setEditor(editor)
                        // content ? console.log(1) : console.log(2);
                        // editor.setContent(content)
                        // editor.disable()
                        editor.on(EventChannel.LocalEvent.TEXT_CHANGED, () => console.log('TEXT_CHANGED'))
                    }}
                    plugins={plugins}
                    module={module}
                />
            </Card>
        </div>
    )
}

export default withRouter(Form.create()(UpdateNew))
